from django.shortcuts import render
from rest_framework.response import Response
from rest_framework_jwt.settings import api_settings
from rest_framework.views import APIView
from rest_framework import status
from django_redis import get_redis_connection

import logging

log = logging.Logger("django")


def connect_redis(cache_key):
    """

    :param cache_key: 配置文件中缓存设置的配置名
    :return:
    """
    redis_conn = get_redis_connection(cache_key)

    return redis_conn


# 用户的登录 注册

"""
验证码，短信，token 多条件登录


放到redis 进行缓存  token  短信

正则判断，输入数据的格式正确性


redis 减少连接测试，使用事务把多条命令集中发送给redis

"""


# 生成jwt
class User:
    username = "aaa"
    pk = 1
    id = 2


aaa = User()


def generator_jwt_token(user):
    jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
    jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
    jwt_response_payload_handler = api_settings.JWT_RESPONSE_PAYLOAD_HANDLER

    payload = jwt_payload_handler(user)
    print("pay", payload)
    token = jwt_encode_handler(payload)
    print(token)
    """
    token, user=None, request=None
    """
    token = jwt_response_payload_handler(token, aaa)

    print(token)


# 登录视图
class LoginAPIView(APIView):

    def post(self, request, *args, **kwargs):
        pass


# 注册视图
class RegisterAPIView(APIView):

    def post(self, request, *args, **kwargs):
        pass

    def get(self, request, *args, **kwargs):
        generator_jwt_token(aaa)

        # 发送过来的
        sms_code =request.get()
        mobile = request.get()
        # 判断短信验证码是否正确
        conn = connect_redis("sms_code")
        real_sms_code = conn.get("sms_%s" % mobile) # 拿到字符串是byte类型

        if real_sms_code.decode() != sms_code:
            #判断是否相等
            log.error("")

            # 删除数据库的验证码，重新发送
            conn.delete("sms_%s" % mobile)
            return Response('短信验证码错误，重新发送')


        # 成功也删除存储的验证码，防止出现恶意破解
        conn.delete("sms_%s" % mobile)
        return Response('ssss')


# 用户名的校验
class MobileAPIView(APIView):
    """检测手机号是否被注册过"""

    def get(self, request, *args, **kwargs):
        return Response({"message": "手机号已经被注册过"}, status=status.HTTP_400_BAD_REQUEST)
        pass


class UsernameAPIView(APIView):
    def get(self, request, *args, **kwargs):
        pass


from ronglian_sms_sdk import SmsSDK
import random

accId = '8aaf07087ca221d8017cd40af29d0943'
accToken = '8d8cd8a94bb7413eb0704ef8144c6287'
appId = '8aaf07087ca221d8017cd40af37c0949'


# 发送短信验证码
def send_message():
    sdk = SmsSDK(accId, accToken, appId)
    tid = '1'
    mobile = '17635395714'
    datas = ('1234',)
    resp = sdk.sendMessage(tid, mobile, datas)
    print(resp)


send_message()


# 发送短信视图
class SendMessageAPIView(APIView):

    def get(self, request, *args, **kwargs):
        # 获取手机号
        mobile = request.get

        # 判断短信在60秒内是否发送过短信
        conn = connect_redis("sms_code")
        res = conn.get("mobile_%s" % mobile)
        if res is not None:
            return Response({"message":"对不起，60秒内已发送"})


        sms_code = "%d" % random.randint(100000, 999999)

        # 验证码，保存到redis

        timer = 5 * 60  # 5分钟
        conn.setex("sms_%s" % mobile, timer, sms_code)  # 过期时间
        conn.setex("mobile_%s" % mobile, 60,'_')  # 60内不要发送 ，时间间隔

        """
        使用redis事务进行，减少连接次数 ，事务只能写操作，读取数据不能使用事务
        pipe = conn.pipeline()   创建管道
        pipe.multi()   开启事务
        # 把事务中要完成的所有操作，写入管道中
        pipe.setex("sms_%s" % mobile, timer, sms_code)  # 过期时间
        pipe.setex("mobile_%s" % mobile, 60,'_')  # 60内不要发送 ，时间间隔
        # 执行事务
        pipe.execute()
        """


        # 发送短信
        try:
            send_message()
        except:
            return Response({"message":"发送短信失败"})

        return Response({"message":"发送短信成功"})
